package com.cloudcc.mobile.im.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.callback.IFooterCallBack;
import com.cloudcc.mobile.R;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.easeui.ui.EaseGroupRemoveListener;
import com.easemob.easeui.utils.EaseUserUtils;
import com.easemob.easeui.widget.EaseAlertDialog;
import com.easemob.easeui.widget.EaseAlertDialog.AlertDialogUser;
import com.easemob.easeui.widget.EaseExpandGridView;
import com.easemob.easeui.widget.EaseSwitchButton;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.EMLog;
import com.easemob.util.NetUtils;

import static com.cloudcc.mobile.R.id.rl_change_group_name;

public class GroupGridActivity extends BaseActivity implements
        OnClickListener {
    private static final String TAG = "GroupGridActivity";
    private static final int REQUEST_CODE_ADD_USER = 0;
    private static final int REQUEST_CODE_EXIT = 1;
    private static final int REQUEST_CODE_EXIT_DELETE = 2;
    private static final int REQUEST_CODE_EDIT_GROUPNAME = 5;

    private EaseExpandGridView userGridview;
    private String groupId;
    private ProgressBar loadingPB;
    private Button exitBtn,clearValue;
    private Button deleteBtn;
    private EMGroup group;
    private GridAdapter adapter;
    private ProgressDialog progressDialog;
    private TextView tv_ckgd;
    private RelativeLayout rl_switch_block_groupmsg;
    private RelativeLayout regone;
    private ScrollView scrollview_x;
    public static GroupGridActivity instance;

    String st = "";
    // 清空所有聊天记录
    private RelativeLayout clearAllHistory;
    private RelativeLayout blacklistLayout;
    private RelativeLayout changeGroupNameLayout;
    private RelativeLayout idLayout;
    private TextView idText;
    private EaseSwitchButton switchButton;
    private GroupRemoveListener groupRemoveListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 获取传过来的groupid
        groupId = getIntent().getStringExtra("groupId");
        group = EMGroupManager.getInstance().getGroup(groupId);

        // we are not supposed to show the group if we don't find the group
        if (group == null) {
            finish();
            return;
        }

        setContentView(R.layout.em_activity_group_details);
        instance = this;
        st = getResources().getString(R.string.people);
        clearAllHistory = (RelativeLayout) findViewById(R.id.clear_all_history);
        userGridview = (EaseExpandGridView) findViewById(R.id.gridview);
        regone = (RelativeLayout)findViewById(R.id.regone);
        loadingPB = (ProgressBar) findViewById(R.id.progressBar);
        exitBtn = (Button) findViewById(R.id.btn_exit_grp);
        clearValue = (Button) findViewById(R.id.btn_clear_value);
        deleteBtn = (Button) findViewById(R.id.btn_exitdel_grp);
        blacklistLayout = (RelativeLayout) findViewById(R.id.rl_blacklist);
        changeGroupNameLayout = (RelativeLayout) findViewById(rl_change_group_name);
        idLayout = (RelativeLayout) findViewById(R.id.rl_group_id);
        tv_ckgd = (TextView)findViewById(R.id.tv_ckgd);
        scrollview_x = (ScrollView)findViewById(R.id.scrollview_x);
        idText = (TextView) findViewById(R.id.tv_group_id_value);

        rl_switch_block_groupmsg = (RelativeLayout) findViewById(R.id.rl_switch_block_groupmsg);
        switchButton = (EaseSwitchButton) findViewById(R.id.switch_btn);
        //gone
        scrollview_x.setBackgroundResource(R.color.white);
        idLayout.setVisibility(View.GONE);
        clearAllHistory.setVisibility(View.GONE);
        blacklistLayout.setVisibility(View.GONE);
        tv_ckgd.setVisibility(View.GONE);
        rl_switch_block_groupmsg.setVisibility(View.GONE);
        changeGroupNameLayout.setVisibility(View.GONE);
        rl_switch_block_groupmsg.setOnClickListener(this);
        clearValue.setVisibility(View.GONE);
        regone.setVisibility(View.GONE);
        idText.setText(groupId);
        if (group.getOwner() == null
                || "".equals(group.getOwner())
                || !group.getOwner().equals(
                EMChatManager.getInstance().getCurrentUser())) {
        }
        // 如果自己是群主，显示解散按钮
        if (EMChatManager.getInstance().getCurrentUser()
                .equals(group.getOwner())) {
        }

        groupRemoveListener = new GroupRemoveListener();
        EMGroupManager.getInstance()
                .addGroupChangeListener(groupRemoveListener);

        ((TextView) findViewById(R.id.group_name)).setText(group.getGroupName());
        tv_ckgd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext,GroupGridActivity.class));
            }
        });
        List<String> members = new ArrayList<String>();
        members.addAll(group.getMembers());

        adapter = new GridAdapter(this, R.layout.em_grid, members);
        userGridview.setAdapter(adapter);

        // 保证每次进详情看到的都是最新的group
        updateGroup();

        // 设置OnTouchListener
        userGridview.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (adapter.isInDeleteMode) {
                            adapter.isInDeleteMode = false;
                            adapter.notifyDataSetChanged();
                            return true;
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

        clearAllHistory.setOnClickListener(this);
        blacklistLayout.setOnClickListener(this);
        changeGroupNameLayout.setOnClickListener(this);

    }
    private String ReturnName;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String st1 = getResources().getString(R.string.being_added);
        String st2 = getResources().getString(R.string.is_quit_the_group_chat);
        String st3 = getResources().getString(R.string.chatting_is_dissolution);
        String st4 = getResources().getString(R.string.are_empty_group_of_news);
        String st5 = getResources()
                .getString(R.string.is_modify_the_group_name);
        final String st6 = getResources().getString(
                R.string.Modify_the_group_name_successful);
        final String st7 = getResources().getString(
                R.string.change_the_group_name_failed_please);

        if (resultCode == RESULT_OK) {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(GroupGridActivity.this);
                progressDialog.setMessage(st1);
                progressDialog.setCanceledOnTouchOutside(false);
            }
            switch (requestCode) {
                case REQUEST_CODE_ADD_USER:// 添加群成员
                    final String[] newmembers = data
                            .getStringArrayExtra("newmembers");
                    progressDialog.setMessage(st1);
                    progressDialog.show();
                    addMembersToGroup(newmembers);
                    break;
                case REQUEST_CODE_EXIT: // 退出群
                    progressDialog.setMessage(st2);
                    progressDialog.show();
                    exitGrop();
                    break;
                case REQUEST_CODE_EXIT_DELETE: // 解散群
                    progressDialog.setMessage(st3);
                    progressDialog.show();
                    deleteGrop();
                    break;

                case REQUEST_CODE_EDIT_GROUPNAME: // 修改群名称
                    final String returnData = data.getStringExtra("data");
                    ReturnName = returnData;
                    if (!TextUtils.isEmpty(returnData)) {
                        progressDialog.setMessage(st5);
                        progressDialog.show();

                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    EMGroupManager.getInstance().changeGroupName(
                                            groupId, returnData);
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            ((TextView) findViewById(R.id.group_name)).setText(returnData
                                                    + "("
                                                    + group.getAffiliationsCount()
                                                    + st);
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(),
                                                    st6, 0).show();
                                        }
                                    });

                                } catch (EaseMobException e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(),
                                                    st7, 0).show();
                                        }
                                    });
                                }
                            }
                        }).start();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    protected void addUserToBlackList(final String username) {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage(getString(R.string.Are_moving_to_blacklist));
        pd.show();
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMGroupManager.getInstance().blockUser(groupId, username);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            refreshMembers();
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(),
                                    R.string.Move_into_blacklist_success, 0)
                                    .show();
                        }
                    });
                } catch (EaseMobException e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(),
                                    R.string.failed_to_move_into, 0).show();
                        }
                    });
                }
            }
        }).start();
    }

    private void refreshMembers() {
        adapter.clear();

        List<String> members = new ArrayList<String>();
        members.addAll(group.getMembers());
        adapter = new GridAdapter(this, R.layout.em_grid, members);
        userGridview.setAdapter(adapter);
    }

    /**
     * 点击退出群组按钮
     *
     * @param view
     */
    public void exitGroup(View view) {
        startActivityForResult(new Intent(this, ExitGroupDialog.class),
                REQUEST_CODE_EXIT);

    }
    /*
     * 点击清空记录
     * */
    public void clearValue(View view) {
        String st9 = getResources().getString(R.string.sure_to_empty_this);
        new EaseAlertDialog(GroupGridActivity.this, null, st9, null,
                new AlertDialogUser() {

                    @Override
                    public void onResult(boolean confirmed, Bundle bundle) {
                        if (confirmed) {
                            clearGroupHistory();
                        }
                    }
                }, true).show();


    }
    /**
     * 点击解散群组按钮
     *
     * @param view
     */
    public void exitDeleteGroup(View view) {
        startActivityForResult(
                new Intent(this, ExitGroupDialog.class).putExtra("deleteToast",
                        getString(R.string.dissolution_group_hint)),
                REQUEST_CODE_EXIT_DELETE);

    }

    /**
     * 清空群聊天记录
     */
    private void clearGroupHistory() {

        EMChatManager.getInstance().clearConversation(group.getGroupId());
        Toast.makeText(this, R.string.messages_are_empty, 0).show();
    }

    /**
     * 退出群组
     *
     * @param groupId
     */
    private void exitGrop() {
        String st1 = getResources().getString(
                R.string.Exit_the_group_chat_failure);
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMGroupManager.getInstance().exitFromGroup(groupId);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            setResult(RESULT_OK);
                            finish();
                            if (ChatActivity.activityInstance != null)
                                ChatActivity.activityInstance.finish();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(
                                    getApplicationContext(),
                                    getResources()
                                            .getString(
                                                    R.string.Exit_the_group_chat_failure)
                                            + " " + e.getMessage(), 1).show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 解散群组
     *
     * @param groupId
     */
    private void deleteGrop() {
        final String st5 = getResources().getString(
                R.string.Dissolve_group_chat_tofail);
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMGroupManager.getInstance().exitAndDeleteGroup(groupId);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            setResult(RESULT_OK);
                            finish();
                            if (ChatActivity.activityInstance != null)
                                ChatActivity.activityInstance.finish();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(),
                                    st5 + e.getMessage(), 1).show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 增加群成员
     *
     * @param newmembers
     */
    private void addMembersToGroup(final String[] newmembers) {
        final String st6 = getResources().getString(
                R.string.Add_group_members_fail);
        new Thread(new Runnable() {

            public void run() {
                try {
                    // 创建者调用add方法
                    if (EMChatManager.getInstance().getCurrentUser()
                            .equals(group.getOwner())) {
                        EMGroupManager.getInstance().addUsersToGroup(groupId,
                                newmembers);
                    } else {
                        // 一般成员调用invite方法
                        EMGroupManager.getInstance().inviteUser(groupId,
                                newmembers, null);
                    }
                    runOnUiThread(new Runnable() {
                        public void run() {
                            refreshMembers();
                            ((TextView) findViewById(R.id.group_name))
                                    .setText(group.getGroupName() );
                            progressDialog.dismiss();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(),
                                    st6 + e.getMessage(), 1).show();
                        }
                    });
                }
            }
        }).start();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_switch_block_groupmsg: // 屏蔽或取消屏蔽群组
                toggleBlockGroup();
                break;

            case R.id.clear_all_history: // 清空聊天记录
                String st9 = getResources().getString(R.string.sure_to_empty_this);
                new EaseAlertDialog(GroupGridActivity.this, null, st9, null,
                        new AlertDialogUser() {

                            @Override
                            public void onResult(boolean confirmed, Bundle bundle) {
                                if (confirmed) {
                                    clearGroupHistory();
                                }
                            }
                        }, true).show();

                break;

            case R.id.rl_blacklist: // 黑名单列表
                break;

            case rl_change_group_name:
                startActivityForResult(
                        new Intent(this, EditActivity.class).putExtra("data",
                                group.getGroupName()), REQUEST_CODE_EDIT_GROUPNAME);
                break;

            default:
                break;
        }

    }

    private void toggleBlockGroup() {
        if (switchButton.isSwitchOpen()) {
            EMLog.d(TAG, "change to unblock group msg");
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(GroupGridActivity.this);
                progressDialog.setCanceledOnTouchOutside(false);
            }
            progressDialog.setMessage(getString(R.string.Is_unblock));
            progressDialog.show();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        EMGroupManager.getInstance().unblockGroupMessage(
                                groupId);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                switchButton.closeSwitch();
                                progressDialog.dismiss();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            public void run() {
                                progressDialog.dismiss();
                                Toast.makeText(getApplicationContext(),
                                        R.string.remove_group_of, 1).show();
                            }
                        });

                    }
                }
            }).start();

        } else {
            String st8 = getResources().getString(R.string.group_is_blocked);
            final String st9 = getResources().getString(
                    R.string.group_of_shielding);
            EMLog.d(TAG, "change to block group msg");
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(GroupGridActivity.this);
                progressDialog.setCanceledOnTouchOutside(false);
            }
            progressDialog.setMessage(st8);
            progressDialog.show();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        EMGroupManager.getInstance().blockGroupMessage(groupId);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                switchButton.openSwitch();
                                progressDialog.dismiss();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            public void run() {
                                progressDialog.dismiss();
                                Toast.makeText(getApplicationContext(), st9, 1)
                                        .show();
                            }
                        });
                    }

                }
            }).start();
        }
    }

    /**
     * 群组成员gridadapter
     *
     * @author admin_new
     *
     */
    private class GridAdapter extends ArrayAdapter<String> {

        private int res;
        public boolean isInDeleteMode;
        public boolean count15;
        private List<String> objects;

        public GridAdapter(Context context, int textViewResourceId,
                           List<String> objects) {
            super(context, textViewResourceId, objects);
            this.objects = objects;
            res = textViewResourceId;
            isInDeleteMode = false;

            if(group.getAffiliationsCount()>11) {
                count15=true;
            }else {
                count15=false;
            }
        }
        @Override
        public View getView(final int position, View convertView,
                            final ViewGroup parent) {
            ViewHolder holder = null;
//			if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(res,
                    null);
            holder.imageView = (ImageView) convertView
                    .findViewById(R.id.iv_avatar);
            holder.textView = (TextView) convertView
                    .findViewById(R.id.tv_name);
            holder.badgeDeleteView = (ImageView) convertView
                    .findViewById(R.id.badge_delete);
            holder.button = (LinearLayout)convertView.findViewById(R.id.button_avatar);
            convertView.setTag(holder);
            holder.button.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    isInDeleteMode = true;
                    notifyDataSetChanged();
                    if (!group.getOwner().equals(
                            EMChatManager.getInstance().getCurrentUser())) {
                        // if current user is not group admin, hide add/remove btn
                    } else { // 显示删除按钮
                        if (isInDeleteMode) {
                            // 正处于删除模式下，隐藏删除按钮
                        } else {
                            // 正常模式
                        }

                    }
                    return true;
                }
            });
//			} else {
//				holder = (ViewHolder) convertView.getTag();
//			}
            final LinearLayout button = (LinearLayout) convertView
                    .findViewById(R.id.button_avatar);
            // 最后一个item，减人按钮
//			if (position == getCount() - 1) {
//				holder.textView.setText("");
//				// 设置成删除按钮
//				holder.imageView
//						.setImageResource(R.drawable.em_smiley_minus_btn);
//				// button.setCompoundDrawablesWithIntrinsicBounds(0,
//				// R.drawable.smiley_minus_btn, 0, 0);
//				// 如果不是创建者或者没有相应权限，不提供加减人按钮
//				if (!group.getOwner().equals(
//						EMChatManager.getInstance().getCurrentUser())) {
//					// if current user is not group admin, hide add/remove btn
//					convertView.setVisibility(View.INVISIBLE);
//				} else { // 显示删除按钮
//					if (isInDeleteMode) {
//						// 正处于删除模式下，隐藏删除按钮
//						convertView.setVisibility(View.INVISIBLE);
//					} else {
//						// 正常模式
//						convertView.setVisibility(View.VISIBLE);
//						convertView.findViewById(R.id.badge_delete)
//								.setVisibility(View.INVISIBLE);
//					}
//					final String st10 = getResources().getString(
//							R.string.The_delete_button_is_clicked);
//					button.setOnClickListener(new OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							EMLog.d(TAG, st10);
//							isInDeleteMode = true;
//							notifyDataSetChanged();
//						}
//					});
//				}
//			} else if
            if(position == getCount() - 1) { // 添加群组成员按钮
                holder.imageView.setImageResource(R.drawable.em_smiley_add_btn);
                // button.setCompoundDrawablesWithIntrinsicBounds(0,
                // R.drawable.smiley_add_btn, 0, 0);
                // 如果不是创建者或者没有相应权限
                if (!group.isAllowInvites()
                        && !group.getOwner().equals(
                        EMChatManager.getInstance().getCurrentUser())) {
                    // if current user is not group admin, hide add/remove btn
                    convertView.setVisibility(View.INVISIBLE);
                } else {
                    // 正处于删除模式下,隐藏添加按钮
                    if (isInDeleteMode) {
                        convertView.setVisibility(View.INVISIBLE);
                    } else {
                        convertView.setVisibility(View.VISIBLE);
                        convertView.findViewById(R.id.badge_delete)
                                .setVisibility(View.INVISIBLE);
                    }
                    final String st11 = getResources().getString(
                            R.string.Add_a_button_was_clicked);
                    button.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
//							EMLog.d(TAG, st11);
                            // 进入选人页面
                            startActivityForResult((new Intent(
                                    GroupGridActivity.this,
                                    GroupPickContactsActivity.class).putExtra(
                                    "groupId", groupId)), REQUEST_CODE_ADD_USER);
                        }
                    });
                }
            } else { // 普通item，显示群组成员
                final String username = getItem(position);
                convertView.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
                // Drawable avatar =
                // getResources().getDrawable(R.drawable.default_avatar);
                // avatar.setBounds(0, 0, referenceWidth, referenceHeight);
                // button.setCompoundDrawables(null, avatar, null, null);
                EaseUserUtils.setUserNick(username, holder.textView);
                EaseUserUtils.setUserAvatar(getContext(), username,
                        holder.imageView);
                if (isInDeleteMode) {
                    // 如果是删除模式下，显示减人图标
                    convertView.findViewById(R.id.badge_delete).setVisibility(
                            View.VISIBLE);
                } else {
                    convertView.findViewById(R.id.badge_delete).setVisibility(
                            View.INVISIBLE);
                }
                final String st12 = getResources().getString(
                        R.string.not_delete_myself);
                final String st13 = getResources().getString(
                        R.string.Are_removed);
                final String st14 = getResources().getString(
                        R.string.Delete_failed);
                final String st15 = getResources().getString(
                        R.string.confirm_the_members);
                button.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isInDeleteMode) {
                            // 如果是删除自己，return
                            if (EMChatManager.getInstance().getCurrentUser()
                                    .equals(username)) {
                                new EaseAlertDialog(GroupGridActivity.this,
                                        st12).show();
                                return;
                            }
                            if (!NetUtils.hasNetwork(getApplicationContext())) {
                                Toast.makeText(
                                        getApplicationContext(),
                                        getString(R.string.network_unavailable),
                                        0).show();
                                return;
                            }
                            EMLog.d("group", "remove user from group:"
                                    + username);
                            deleteMembersFromGroup(username);
                        } else {
                            // 正常情况下点击user，可以进入用户详情或者聊天页面等等
                            // startActivity(new
                            // Intent(GroupDetailsActivity.this,
                            // ChatActivity.class).putExtra("userId",
                            // user.getUsername()));

                        }
                    }

                    /**
                     * 删除群成员
                     *
                     * @param username
                     */
                    protected void deleteMembersFromGroup(final String username) {
                        final ProgressDialog deleteDialog = new ProgressDialog(
                                GroupGridActivity.this);
                        deleteDialog.setMessage(st13);
                        deleteDialog.setCanceledOnTouchOutside(false);
                        deleteDialog.show();
                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    // 删除被选中的成员
                                    EMGroupManager.getInstance()
                                            .removeUserFromGroup(groupId,
                                                    username);
                                    isInDeleteMode = false;
                                    runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            deleteDialog.dismiss();
                                            refreshMembers();
                                            ((TextView) findViewById(R.id.group_name)).setText(group
                                                    .getGroupName());
                                        }
                                    });
                                } catch (final Exception e) {
                                    deleteDialog.dismiss();
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            Toast.makeText(
                                                    getApplicationContext(),
                                                    st14 + e.getMessage(), 1)
                                                    .show();
                                        }
                                    });
                                }

                            }
                        }).start();
                    }
                });

                // button.setOnLongClickListener(new OnLongClickListener() {
                //
                // @Override
                // public boolean onLongClick(View v) {
                // if(EMChatManager.getInstance().getCurrentUser().equals(username))
                // return true;
                // if
                // (group.getOwner().equals(EMChatManager.getInstance().getCurrentUser()))
                // {
                // new EaseAlertDialog(GroupDetailsActivity.this, null, st15,
                // null, new AlertDialogUser() {
                //
                // @Override
                // public void onResult(boolean confirmed, Bundle bundle) {
                // if(confirmed){
                // addUserToBlackList(username);
                // }
                // }
                // }, true).show();
                //
                // }
                // return false;
                // }
                // });
            }
            return convertView;
        }

        @Override
        public int getCount() {
            return super.getCount() + 1;


        }
    }

    protected void updateGroup() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    final EMGroup returnGroup = EMGroupManager.getInstance()
                            .getGroupFromServer(groupId);
                    // 更新本地数据
                    EMGroupManager.getInstance().createOrUpdateLocalGroup(
                            returnGroup);

                    runOnUiThread(new Runnable() {
                        public void run() {
                            ((TextView) findViewById(R.id.group_name))
                                    .setText(group.getGroupName() );
                            loadingPB.setVisibility(View.INVISIBLE);
                            refreshMembers();
                            if (EMChatManager.getInstance().getCurrentUser()
                                    .equals(group.getOwner())) {
                                // 显示解散按钮
                                exitBtn.setVisibility(View.GONE);
                                deleteBtn.setVisibility(View.VISIBLE);
                            } else {
                                // 显示退出按钮
                                exitBtn.setVisibility(View.VISIBLE);
                                deleteBtn.setVisibility(View.GONE);
                            }

                            // update block
                            EMLog.d(TAG,
                                    "group msg is blocked:"
                                            + group.getMsgBlocked());
                            if (group.isMsgBlocked()) {
                                switchButton.openSwitch();
                            } else {
                                switchButton.closeSwitch();
                            }
                        }
                    });

                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            loadingPB.setVisibility(View.INVISIBLE);
                        }
                    });
                }
            }
        }).start();
    }

    public void back(View view) {
        setResult(RESULT_OK,
                new Intent().putExtra("rename", ReturnName));
        finish();
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
    }

    private static class ViewHolder {
        ImageView imageView;
        TextView textView;
        ImageView badgeDeleteView;
        LinearLayout button;
    }

    /**
     * 监测群组解散或者被T事件
     *
     */
    private class GroupRemoveListener extends EaseGroupRemoveListener {

        @Override
        public void onUserRemoved(final String groupId, String groupName) {
            finish();
        }

        @Override
        public void onGroupDestroy(final String groupId, String groupName) {
            finish();
        }

    }

}
